<!--
聊天框组件(chat-box)
功能说明:
1. 消息展示与发送
   - 支持文本、图片、文件、语音等多种消息类型
   - 支持消息预览、转发、撤回等操作
   - 支持@功能和群消息已读状态
2. 输入功能
   - 文本输入框
   - 表情选择器
   - 语音录制
   - 图片/文件上传
3. 群聊功能
   - 群成员管理
   - @群成员
   - 群消息回执
4. 其他功能
   - 消息引用
   - 消息收藏
   - 文件处理
-->
<template>
	<view class="page chat-box">
		<!-- <watermark></watermark> -->
		<text style="display: none;">{{title}}</text>
		<!-- <view class="header">
			<uni-icons class="btn-side left" type="back" size="30" @click="onNavBack()"></uni-icons>
			<text class="title">{{title}}</text>
			<uni-icons class="btn-side right" type="more-filled" size="30" @click="onShowMore()"></uni-icons>
		</view> -->
		<text style="display: none;">{{groupInfo}}</text>
		<top-right-tool-wx ref="trtw"></top-right-tool-wx>
		<view class="chat-msg" @click="switchChatTabBox('none',true)">
			<scroll-view class="scroll-box" ref="scrollViewRef" scroll-y="true" upper-threshold="200" @scrolltoupper="onScrollToTop"
				:scroll-into-view="'chat-item-'+scrollMsgIdx">
				<view v-if="chat" v-for="(msgInfo,idx) in chat.messages" :key="idx">
					<chat-message-item v-if="idx>=showMinIdx" :headImage="headImage(msgInfo)"
						@call="onRtCall(msgInfo)" @collect="onCollect" :showName="showName(msgInfo)" @recall="onRecallMessage"
						@copy="onCopyMessage" @delete="onDeleteMessage" @longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile" 
						@recallthis="onRecallthisMessage" @quote="onQuote"  @forward="onForward"
						:id="'chat-item-'+idx" :tagId="idx" :msgInfo="msgInfo" :groupMembers="groupMembers" :isAdmin="isadmin" :groupInfo="AutoAdd" >
					</chat-message-item>
				</view>
			</scroll-view>
		</view>
		<!-- @头像列表 -->
		<view v-if="atUserIds.length>0" class="chat-at-bar" @click="openAtBox()">
			<view class="iconfont icon-at">:&nbsp;</view>
			<scroll-view v-if="atUserIds.length>0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
				<view class="chat-at-items">
					<view v-for="m in atUserItems" class="chat-at-item">
						<head-image :name="m.showNickName" :url="m.headImage" :size="50"></head-image>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 引用消息 -->
		<view v-if="quoteShow" >
			<u-alert :isShow="quoteShow" class="ellipsis-alert" @click="positioningMsg" type = "info" :description = "value4" :closable="true" @close="onClose"></u-alert>
		</view>
		
		<view class="send-bar">
			<template v-if="!isProhibition">
				<view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view>
				<view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view>
			</template>
			<chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record>
			<view v-else class="send-text">
				<textarea :disabled="isProhibition" :style="mystyle" class="send-text-area" v-model="sendText" auto-height :show-confirm-bar="false"
					:placeholder="isReceipt?'[回执消息]':''" :adjust-position="false" @confirm="sendTextMessage()"
					@keyboardheightchange="onKeyboardheightchange" @input="onTextInput" confirm-type="send" confirm-hold
					:hold-keyboard="true" :maxlength="-1" :cursor-spacing="10"></textarea>
			</view>
			<view v-if="chat && chat.type=='GROUP'&&!isProhibition" class="iconfont icon-at" @click="openAtBox()"></view>
			<view v-if="!isProhibition" class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view>
			<view v-if="sendText==''&&!isProhibition" class="iconfont icon-add" @click="onShowToolsChatTab()">
			</view>
			<button v-if="(sendText!=''&&!isProhibition)||atUserIds.length>0" class="btn-send" type="primary"
				@touchend.prevent="sendTextMessage()" size="mini">发送</button>
		</view>

		<view class="chat-tab-bar" v-show="chatTabBox!='none' ||showKeyBoard " :style="{height:`${keyboardHeight}px`}">
			<view v-if="chatTabBox == 'tools'" class="chat-tools">
				<view class="chat-tools-item">
					<view class="tool-icon iconfont icon-picture" @click="handleAlbumClick"></view>
					<view class="tool-name">相册</view>
				</view>
				<view class="chat-tools-item">
					<view class="tool-icon iconfont icon-camera" @click="handleCameraClick"></view>
					<view class="tool-name">拍摄</view>
				</view>
				
				<view class="chat-tools-item">
					<file-upload ref="fileUploadRef" v-if="permission" :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
						:onError="onUploadFileFail">
						<view class="tool-icon iconfont icon-folder"></view>
					</file-upload>
					<view v-if="!permission" class="tool-icon iconfont icon-folder" @click="handleFileClick"></view>
					<view class="tool-name">文件</view>
				</view>
				
				

				<view class="chat-tools-item" @click="onRecorderInput()">
					<view class="tool-icon iconfont icon-microphone" ></view>
					<view class="tool-name">语音消息</view>
				</view>
				<view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="switchReceipt()">
					<view class="tool-icon iconfont icon-receipt" 
						:class="isReceipt?'active':''"></view>
					<view class="tool-name">回执消息</view>
				</view>
				<!-- #ifndef MP-WEIXIN -->
				<!-- 音视频不支持小程序 -->
				<!-- <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVideo()">
					<view class="tool-icon iconfont icon-video" ></view>
					<view class="tool-name">视频通话</view>
				</view>
				<view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVoice()">
					<view class="tool-icon iconfont icon-call" ></view>
					<view class="tool-name">语音通话</view>
				</view>
				<view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="onGroupVideo()">
					<view class="tool-icon iconfont icon-call" ></view>
					<view class="tool-name">语音通话</view>
				</view> -->
				<!-- #endif -->
			</view>
			<scroll-view v-if="chatTabBox==='emo'" class="chat-emotion" scroll-y="true">
				<view class="emotion-item-list">
					<image class="emotion-item" :title="emoText" :src="$emo.textToPath(emoText)"
						v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
						lazy-load="true"></image>
				</view>
			</scroll-view>
			<view v-if="showKeyBoard"></view>
		</view>
		<!-- @用户时选择成员 -->
		<chat-at-box ref="atBox" :ownerId="group.ownerId" :id="atUserIds" :members="groupMembers"
			@complete="onAtComplete"></chat-at-box>
			
		<!-- 转发消息 @close="chatMail"-->
		<chat-forward ref="forward" :ownerId="group.ownerId"
			@complete="onForwardComplete" ></chat-forward>
			
		<!-- 群语音通话时选择成员 -->
		<!-- #ifndef MP-WEIXIN -->
		<group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel" @complete="onInviteOk"></group-member-selector>
		<group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
		<!-- #endif -->
	</view>
</template>

<script>
	import UNI_APP from '@/.env.js';
	import pushApi from '../../api/im/collect';
	import groupMember from '../../api/im/groupMember.js'
	import groupApi from '../../api/im/group';
	import systemApi from '../../api/im/system';
	import { requestPermissionWithExplanation } from '@/common/permission.js'
	import SystemMessageDetail from '@/components/system-message/system-message.vue';
	export default {
		data() {
			return {
				chat: {},
				friend: {},
				group: {},
				groupMembers: [],
				sendText: "",//全  员   禁   言
				isReceipt: false, // 是否回执消息
				scrollMsgIdx: 0, // 滚动条定位为到哪条消息
				chatTabBox: 'none',
				showKeyBoard: false,
				showRecord: false,
				keyboardHeight: 322,
				atUserIds: [],
				needScrollToBottom: false, // 需要滚动到底部 
				showMinIdx: 0, 	// 下标小于showMinIdx的消息不显示，否则可能很卡
				reqQueue: [], 	// 请求队列
				isSending: false ,// 是否正在发送请求
				isadmin:false,
				isProhibition:false,
				stylea:'left',
				AutoAdd:false,
				quoteShow:false,
				closable:true,
				value4:'',
				targetId:"",
				quoteId:'',
				currentMSGObj:{},
				permission:false,
			}
		},
		onNavigationBarButtonTap(e) {
			switch (e.index) {
				case 0:
				if (this.chat.type == 'GROUP') {
					if(this.chat.lastContent=='您已被移出群聊'||this.chat.lastContent.indexOf('解散')!=-1){
						uni.showModal({
							title: '提示',
							content: this.chat.lastContent, // 设置弹框中的内容
							showCancel: false, // 不显示取消按钮
							confirmText: '我知道了', // 设置确定按钮的文本
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击了"我知道了"按钮');
									// 在这里编写按钮点击后的逻辑
								}
							}
						});
						return ;
					}
					uni.navigateTo({
						url: "/pages/group/group-info?id=" + this.group.id
					})
				}
				if(this.chat.type == 'PRIVATE'){
					uni.navigateTo({
						url:'/pages/friend/personInfo/detail?param='+this.chat.targetId+"&type=1"
					})
				}
				
					break;
				default:
					break;
			}
		},
		methods: {
			/**
			 * 关闭引用消息提示
			 */
			onClose(){
				this.quoteShow=false;
			},

			/**
			 * 定位到引用的消息位置
			 * 通过滚动将引用的消息显示在视图中
			 */
			positioningMsg(){
				if(this.targetId==""){
					return;
				}
				const target = document.getElementById('chat-item-'+(this.targetId-3));
				target.scrollIntoView({
					behavior: 'smooth'
				});
				this.targetId="";
			},

			/**
			 * 处理消息转发
			 * @param {Object} magInfo - 要转发的消息信息
			 */
			onForward(magInfo){
				this.currentMSGObj=magInfo;
				this.$refs.forward.init();
				this.$refs.forward.open();
			},

			/**
			 * 转发消息完成后的回调处理
			 * @param {Array} selectItem - 选中的转发目标列表
			 */
			onForwardComplete(selectItem){
				let msgInfo={};
				let type =this.currentMSGObj.type;
				let content=this.currentMSGObj.content;
				selectItem.forEach((item)=>{
					msgInfo={};
					if (item.type == "GROUP") {
						msgInfo.groupId = item.targetId;
					} else {
						msgInfo.recvId = item.targetId;
					}
					msgInfo.chatType=item.type;
					msgInfo.sendNickName=item.sendNickName;
					
					// 根据消息类型构造转发消息
					if(type==this.$enums.MESSAGE_TYPE.TEXT){
						msgInfo.content=content;
						msgInfo.atUserIds= this.atUserIds;
						msgInfo.sendTime = new Date().getTime();
						msgInfo.receipt=false;
						msgInfo.type=0;
						this.sendMessageRequest2(msgInfo).then((m) => {
							uni.showToast({
								title:'已发送',
								icon:'none'
							})
						});
					}else if(type==this.$enums.MESSAGE_TYPE.IMAGE){
						msgInfo.id=0;
						msgInfo.tmpId = this.generateId();
						msgInfo.fileId = null;
						msgInfo.sendId = this.mine.id;
						msgInfo.content = content;
						msgInfo.sendTime = new Date().getTime();
						msgInfo.selfSend = true;
						msgInfo.type = this.$enums.MESSAGE_TYPE.IMAGE;
						msgInfo.readedCount = 0;
						msgInfo.loadStatus =  "loading";
						msgInfo.status = this.$enums.MESSAGE_STATUS.UNSEND;
						this.sendMessageRequest2(msgInfo).then((m) => {
							uni.showToast({
								title:'已发送',
								icon:'none'
							})
						});
					}else if(type==this.$enums.MESSAGE_TYPE.FILE){
						msgInfo.id = 0;
						msgInfo.tmpId = this.generateId(),
						msgInfo.sendId = this.mine.id,
						msgInfo.content = content,
						msgInfo.sendTime = new Date().getTime(),
						msgInfo.selfSend = true,
						msgInfo.type = this.$enums.MESSAGE_TYPE.FILE,
						msgInfo.readedCount = 0,
						msgInfo.loadStatus = "loading",
						msgInfo.status = this.$enums.MESSAGE_STATUS.UNSEND
						this.sendMessageRequest2(msgInfo).then((m) => {
							uni.showToast({
								title:'已发送',
								icon:'none'
							})
						});
					}else if(type==this.$enums.MESSAGE_TYPE.AUDIO){
						msgInfo = {
							content:content ,
							type: this.$enums.MESSAGE_TYPE.AUDIO,
							receipt: false
						}
						this.sendMessageRequest2(msgInfo).then((m) => {
							uni.showToast({
								title:'已发送',
								icon:'none'
							})
						});
					}
				})
			},

			/**
			 * 处理消息引用
			 * @param {Object} magInfo - 被引用的消息信息
			 */
			onQuote(magInfo){
				this.quoteShow=true;
				this.closable=true
				let text=magInfo.content;
				switch(magInfo.type) {
					case this.$enums.MESSAGE_TYPE.IMAGE:
						text='[图片]';
						break;
					case this.$enums.MESSAGE_TYPE.FILE:
						text='[文件]';
						break;
					case this.$enums.MESSAGE_TYPE.AUDIO:
						text='[语音]';
						break;
				}
				this.value4=magInfo.sendNickName+" : "+text;
				this.targetId=magInfo.tagId;
				this.quoteId=magInfo.id;
			},

			/**
			 * 切换到语音录制模式
			 */
			onRecorderInput() {
				this.showRecord = true;
				this.switchChatTabBox('none', true);
			},

			/**
			 * 切换到键盘输入模式
			 */
			onKeyboardInput() {
				this.showRecord = false;
				this.switchChatTabBox('none', false);
			},

			/**
			 * 发送语音消息
			 * @param {Object} data - 语音数据
			 */
			onSendRecord(data) {
				let msgInfo = {
					content: JSON.stringify(data),
					type: this.$enums.MESSAGE_TYPE.AUDIO,
					receipt: this.isReceipt
				}
				if(this.quoteShow){
					msgInfo.quoteId=this.quoteId;
				}
				this.fillTargetId(msgInfo, this.chat.targetId);
				this.sendMessageRequest(msgInfo).then((m) => {
					m.selfSend = true;
					this.chatStore.insertMessage(m);
					this.quoteShow=false;
					this.moveChatToTop();
					this.scrollToBottom();
					this.isReceipt = false;
				})
			},

			/**
			 * 处理音视频通话请求
			 * @param {Object} msgInfo - 通话消息信息
			 */
			onRtCall(msgInfo) {
				if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
					this.onPriviteVoice();
				} else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
					this.onPriviteVideo();
				}
			},

			/**
			 * 发起私聊视频通话
			 */
			onPriviteVideo() {
				const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
				uni.navigateTo({
					url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`
				})
			},

			/**
			 * 发起私聊语音通话
			 */
			onPriviteVoice() {
				const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
				uni.navigateTo({
					url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`
				})
			},

			/**
			 * 发起群组视频通话
			 */
			onGroupVideo() {
				this.$http({
					url: "/webrtc/group/info?groupId="+this.group.id,
					method: 'GET'
				}).then((rtcInfo)=>{
					if(rtcInfo.isChating){
						this.$refs.rtcJoin.open(rtcInfo);
					}else {
						let ids = [this.mine.id];
						this.$refs.selBox.init(ids, ids);
						this.$refs.selBox.open();
					}
				})
			},

			/**
			 * 群组通话成员选择完成回调
			 * @param {Array} ids - 选中的成员ID列表
			 */
			onInviteOk(ids) {
				if(ids.length < 2){
					return;
				}
				let users = [];
				ids.forEach(id => {
					let m = this.groupMembers.find(m => m.userId == id);
					users.push({
						id: m.userId,
						nickName: m.showNickName,
						headImage: m.headImage,
						isCamera: false,
						isMicroPhone: true
					})
				})
				const groupId = this.group.id;
				const inviterId = this.mine.id;
				const userInfos = encodeURIComponent(JSON.stringify(users));
				
				uni.navigateTo({
					url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true&inviterId=${inviterId}&userInfos=${userInfos}`
				})
			},

			/**
			 * 将当前会话移到会话列表顶部
			 */
			moveChatToTop() {
				let chatIdx = this.chatStore.findChatIdx(this.chat);
				this.chatStore.moveTop(chatIdx);
			},

			/**
			 * 切换回执消息状态
			 */
			switchReceipt() {
				this.isReceipt = !this.isReceipt;
			},

			/**
			 * 打开@用户选择框
			 */
			openAtBox() {
				this.$refs.atBox.init(this.atUserIds);
				this.$refs.atBox.open();
			},

			/**
			 * @用户选择完成回调
			 * @param {Array} atUserIds - 选中的用户ID列表
			 */
			onAtComplete(atUserIds) {
				this.atUserIds = atUserIds;
			},

			/**
			 * 长按用户头像处理
			 * @param {Object} msgInfo - 消息信息
			 */
			onLongPressHead(msgInfo) {
				if (!msgInfo.selfSend && this.chat.type == "GROUP" && this.atUserIds.indexOf(msgInfo.sendId) < 0) {
					this.atUserIds.push(msgInfo.sendId);
				}
			},

			/**
			 * 获取消息发送者头像
			 * @param {Object} msgInfo - 消息信息
			 * @returns {string} 头像URL
			 */
			headImage(msgInfo) {
				if (this.chat.type == 'GROUP') {
					let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
					return member ? member.headImage : "";
				} else {
					return msgInfo.selfSend ? this.mine.headImage : this.chat.headImage
				}
			},

			/**
			 * 获取消息发送者显示名称
			 * @param {Object} msgInfo - 消息信息
			 * @returns {string} 显示名称
			 */
			showName(msgInfo) {
				if (this.chat.type == 'GROUP') {
					let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
					return member ? member.showNickName : "";
				} else {
					return msgInfo.selfSend ? this.mine.nickName : this.chat.showName
				}
			},

			/**
			 * 发送文本消息
			 */
			sendTextMessage() {
				if (!this.sendText.trim() && this.atUserIds.length == 0) {
					return uni.showToast({
						title: "不能发送空白信息",
						icon: "none"
					});
				}
				let receiptText = this.isReceipt ? "【回执消息】" : "";
				let atText = this.createAtText();
				let msgInfo = {
					content: receiptText + this.sendText + atText,
					atUserIds: this.atUserIds,
					receipt: this.isReceipt,
					type: 0
				}
				if(this.quoteShow){
					msgInfo.quoteId=this.quoteId;
				}
				this.sendText = "";
				this.fillTargetId(msgInfo, this.chat.targetId);
				this.sendMessageRequest(msgInfo).then((m) => {
					m.selfSend = true;
					this.chatStore.insertMessage(m);
					this.quoteShow=false;
					this.moveChatToTop();
				}).finally(() => {
					this.scrollToBottom();
					this.atUserIds = [];
					this.isReceipt = false;
				});
			},

			/**
			 * 生成@用户文本
			 * @returns {string} @用户文本
			 */
			createAtText() {
				let atText = "";
				this.atUserIds.forEach((id) => {
					if (id == -1) {
						atText += ` @全体成员`;
					} else {
						let member = this.groupMembers.find((m) => m.userId == id);
						if (member) {
							atText += ` @${member.showNickName}`;
						}
					}
				})
				return atText;
			},

			/**
			 * 填充消息目标ID
			 * @param {Object} msgInfo - 消息信息
			 * @param {string|number} targetId - 目标ID
			 */
			fillTargetId(msgInfo, targetId) {
				if (this.chat.type == "GROUP") {
					msgInfo.groupId = targetId;
				} else {
					msgInfo.recvId = targetId;
				}
			},

			/**
			 * 滚动到消息列表底部
			 */
			scrollToBottom() {
				let size = this.messageSize;
				if (size > 0) {
					this.scrollToMsgIdx(size - 1);
				}
			},

			/**
			 * 滚动到指定消息位置
			 * @param {number} idx - 消息索引
			 */
			scrollToMsgIdx(idx) {
				if (idx == this.scrollMsgIdx && idx > 0) {
					this.$nextTick(() => {
						this.scrollMsgIdx = idx - 1;
						this.scrollToMsgIdx(idx);
					});
					return;
				}
				this.$nextTick(() => {
					this.scrollMsgIdx = idx;
				});
			},

			/**
			 * 显示表情选择面板
			 */
			onShowEmoChatTab() {
				this.showRecord = false;
				this.switchChatTabBox('emo', true)
			},

			/**
			 * 显示工具选择面板
			 */
			onShowToolsChatTab() {
				this.showRecord = false;
				this.switchChatTabBox('tools', true)
			},

			/**
			 * 切换底部功能面板
			 * @param {string} chatTabBox - 面板类型
			 * @param {boolean} hideKeyBoard - 是否隐藏键盘
			 */
			switchChatTabBox(chatTabBox, hideKeyBoard) {
				this.chatTabBox = chatTabBox;
				if (hideKeyBoard) {
					uni.hideKeyboard();
					this.showKeyBoard = false;
				}
			},

			/**
			 * 选择表情
			 * @param {string} emoText - 表情文本
			 */
			selectEmoji(emoText) {
				this.sendText += `#${emoText};`;
			},

			/**
			 * 键盘高度变化处理
			 * @param {Object} e - 事件对象
			 */
			onKeyboardheightchange(e) {
				if (e.detail.height > 0) {
					this.showKeyBoard = true;
					this.switchChatTabBox('none', false)
					this.keyboardHeight = this.rpxTopx(e.detail.height);
					this.scrollToBottom();
				} else {
					this.showKeyBoard = false;
				}
			},

			/**
			 * 复制消息内容
			 * @param {Object} msgInfo - 消息信息
			 */
			onCopyMessage(msgInfo) {
				uni.setClipboardData({
					data: msgInfo.content,
					success: () => {
						uni.showToast({ title: '已复制', icon: 'none' });
					},
					fail: () => {
						uni.showToast({ title: '复制失败', icon: 'none' });
					}
				});
			},

			/**
			 * 文件上传前处理
			 * @param {Object} file - 文件对象
			 * @returns {Promise|boolean} 处理结果
			 */
			onUploadFileBefore(file) {
				// #ifdef APP-PLUS
				if(plus.os.name.toLowerCase() === 'android') {
					const permissionName = 'android.permission.READ_EXTERNAL_STORAGE';
						
					return requestPermissionWithExplanation(permissionName)
						.then(() => {
							return this.createFileMessage(file);
						})
						.catch(() => {
							uni.showToast({
								title: '未获得存储权限',
								icon: 'none'
							});
							return false;
						});
				} else if(plus.os.name.toLowerCase() === 'ios') {
					return this.createFileMessage(file);
				}
				// #endif
				return true;
			},

			/**
			 * 创建文件消息
			 * @param {Object} file - 文件对象
			 * @returns {boolean} 是否创建成功
			 */
			createFileMessage(file) {
				let msgInfo = {
					id: 0,
					tmpId: this.generateId(),
					fileId: file.uid,
					sendId: this.mine.id,
					content: JSON.stringify({
						name: file.name,
						size: file.size,
						url: file.path
					}),
					sendTime: new Date().getTime(),
					selfSend: true,
					type: this.$enums.MESSAGE_TYPE.FILE,
					readedCount: 0,
					loadStatus: "loading",
					status: this.$enums.MESSAGE_STATUS.UNSEND,
				}
				this.fillTargetId(msgInfo, this.chat.targetId);
				this.chatStore.insertMessage(msgInfo);
				this.quoteShow = false;
				this.moveChatToTop();
				file.msgInfo = msgInfo;
				this.scrollToBottom();
				return true;
			},

			/**
			 * 文件上传成功处理
			 * @param {Object} file - 文件对象
			 * @param {Object} res - 上传响应
			 */
			onUploadFileSuccess(file, res) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				let fileContent = {
					name: file.name,
					size: file.size,
					url: res.data
				};
				msgInfo.content = JSON.stringify(fileContent);
				msgInfo.receipt = this.isReceipt;
				if(this.quoteShow){
					msgInfo.quoteId = this.quoteId;
				}
				this.sendMessageRequest(msgInfo).then((m) => {
					msgInfo.loadStatus = 'ok';
					msgInfo.id = m.id;
					msgInfo.sendNickName = m.sendNickName;
					this.isReceipt = false;
					this.chatStore.insertMessage(msgInfo);
					this.quoteShow = false;
				})
			},

			/**
			 * 文件上传失败处理
			 * @param {Object} file - 文件对象
			 * @param {Object} res - 错误响应
			 */
			onUploadFileFail(file, res) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				msgInfo.loadStatus = 'fail';
				this.chatStore.insertMessage(msgInfo);
				this.quoteShow=false;
			},

			/**
			 * 删除消息
			 * @param {Object} msgInfo - 消息信息
			 */
			onDeleteMessage(msgInfo) {
				uni.showModal({
					title: '删除消息',
					content: '确认删除消息?',
					success: (res) => {
						if (!res.cancel) {
							this.chatStore.deleteMessage(msgInfo);
							uni.showToast({
								title: "删除成功",
								icon: "none"
							})
						}
					}
				})
			},

			/**
			 * 撤回消息
			 * @param {Object} msgInfo - 消息信息
			 */
			onRecallMessage(msgInfo) {
				uni.showModal({
					title: '撤回消息',
					content: '确认撤回消息?',
					success: (res) => {
						if (!res.cancel) {
							let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
							this.$http({
								url: url,
								method: 'DELETE'
							}).then(() => {
								msgInfo = JSON.parse(JSON.stringify(msgInfo));
								msgInfo.type = this.$enums.MESSAGE_TYPE.RECALL;
								msgInfo.content = '你撤回了一条消息';
								msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
								this.chatStore.insertMessage(msgInfo);
							})
						}
					}
				})
			},

			/**
			 * 管理员撤回消息
			 * @param {Object} msgInfo - 消息信息
			 */
			onRecallthisMessage(msgInfo){
				uni.showModal({
					title: '撤回消息',
					content: '确认撤回此条消息?',
					success: (res) => {
						if (!res.cancel) {
							let url = `/message/${this.chat.type.toLowerCase()}/recallAdmin/${msgInfo.id}`
							this.$http({
								url: url,
								method: 'DELETE'
							}).then(() => {
								msgInfo = JSON.parse(JSON.stringify(msgInfo));
								msgInfo.type = this.$enums.MESSAGE_TYPE.RECALL;
								msgInfo.content = '你撤回了一条消息';
								msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
								this.chatStore.insertMessage(msgInfo);
							})
						}
					}
				})
			},

			/**
			 * 收藏消息
			 * @param {Object} msgInfo - 消息信息
			 */
			onCollect(msgInfo){
				uni.showModal({
					title: '收藏消息',
					content: '确认收藏消息?',
					cancelText:'取消',
					confirmText:'确认',
					success: (res) => {
						if (!res.cancel) {
							let forData={
								content:msgInfo.content,
								userId:this.mine.id,
								collectType:msgInfo.type
							}
							pushApi.add(forData).then(res=>{
								if(res){
									uni.showToast({
										title: "收藏成功",
										icon: "none"
									})
								}
							})
						}
					}
				})
			},

			/**
			 * 下载并打开文件
			 * @param {Object} msgInfo - 消息信息
			 */
			onDownloadFile(msgInfo) {
				let url = JSON.parse(msgInfo.content).url;
				uni.downloadFile({
					url: url,
					success(res) {
						if (res.statusCode === 200) {
							var filePath = encodeURI(res.tempFilePath);
							uni.openDocument({
								filePath: filePath,
								success: function () {
									console.log('打开文档成功');
								},
								fail: function() {
									uni.showToast({
										title: '无法打开此类型文件',
										icon: 'none'
									});
								}
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '文件下载失败',
							icon: 'none'
						});
					}
				});
			},

			onScrollToTop() {
				if (this.showMinIdx == 0) {
					console.log("消息已滚动到顶部")
					return;
				}
				//  #ifndef H5
				// 防止滚动条定格在顶部，不能一直往上滚
				this.scrollToMsgIdx(this.showMinIdx);
				// #endif
				// 多展示0条信息
				this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
			},

			onShowMore() {
				if (this.chat.type == "GROUP") {
					uni.navigateTo({
						url: "/pages/group/group-info?id=" + this.group.id
					})
				} else {
					uni.navigateTo({
						url: "/pages/common/user-info?id=" + this.friend.id
					})
				}
			},

			onTextInput(e) {
				let idx = e.detail.cursor - 1;
				if (this.chat.type == 'GROUP' && e.detail.value[idx] == '@') {
					this.openAtBox();
					let sendText = e.detail.value.replace("@", '');
					this.$nextTick(() => {
						this.sendText = sendText;
					})
				}
			},

			loadReaded(fid) {
				this.$http({
					url: `/message/private/maxReadedId?friendId=${fid}`,
					method: 'get'
				}).then((id) => {
					this.chatStore.readedMessage({
						friendId: fid,
						maxId: id
					});
				});
			},

			readedMessage() {
				if (this.unreadCount == 0) {
					return;
				}
				let url = ""
				if (this.chat.type == "GROUP") {
					url = `/message/group/readed?groupId=${this.chat.targetId}`
				} else {
					url = `/message/private/readed?friendId=${this.chat.targetId}`
				}
				this.$http({
					url: url,
					method: 'PUT'
				}).then(() => {
					this.chatStore.resetUnreadCount(this.chat)
					this.scrollToBottom();
				})
			},
			loadGroup(groupId) {
				this.$http({
					url: `/group/find/${groupId}`,
					method: 'GET'
				}).then((group) => {
					this.group = group;
					this.chatStore.updateChatFromGroup(group);
					this.groupStore.updateGroup(group);
				});
				this.$http({
					url: `/group/members/${groupId}`,
					method: 'GET'
				}).then((groupMembers) => {
					this.groupMembers = groupMembers;
				});
			},

			loadFriend(friendId) {
				// 获取对方最新信息
				this.$http({
					url: `/user/find/${friendId}`,
					method: 'GET'
				}).then((friend) => {
					this.friend = friend;
					this.chatStore.updateChatFromFriend(friend);
					this.friendStore.updateFriend(friend);
				})
			},

			rpxTopx(rpx) {
				// px转换成rpx
				let info = uni.getSystemInfoSync()
				let px = info.windowWidth * rpx / 750;
				return Math.floor(rpx);
			},

			sendMessageRequest(msgInfo){
				return  new Promise((resolve,reject)=>{
					// 请求入队列，防止请求"后发先至"，导致消息错序
					this.reqQueue.push({msgInfo,resolve,reject});
					this.processReqQueue();
				})
			},

			processReqQueue(){
				if (this.reqQueue.length && !this.isSending) {
					this.isSending = true;
					const reqData = this.reqQueue.shift();
					this.$http({
						url: this.messageAction,
						method: 'post',
						data: reqData.msgInfo
					}).then((res)=>{
						if(res.groupMessage!=undefined){
							res.groupMessage = res.groupMessage;
						}
						if(res.privateMessage!=undefined){
							res.privateMessage = res.privateMessage;
						}
						reqData.resolve(res);
					}).catch((e)=>{
						reqData.reject(e)
					}).finally(()=>{
						this.isSending = false;
						// 发送下一条请求
						this.processReqQueue();
					})
				}
			},

			sendMessageRequest2(msgInfo){
				return  new Promise((resolve,reject)=>{
					// 请求入队列，防止请求"后发先至"，导致消息错序
					this.reqQueue.push({msgInfo,resolve,reject});
					this.processReqQueue2();
				})
			},

			processReqQueue2(){
				if (this.reqQueue.length && !this.isSending) {
					this.isSending = true;
					const reqData = this.reqQueue.shift();
					let requestUrl=`/message/${reqData.msgInfo.chatType.toLowerCase()}/send`;
					this.$http({
						url: requestUrl,
						method: 'post',
						data: reqData.msgInfo
					}).then((res)=>{
						if(reqData.msgInfo.type==this.$enums.MESSAGE_TYPE.TEXT){
							reqData.msgInfo.selfSend=true;
						}
						reqData.msgInfo.sendNickName=res.sendNickName;
						reqData.msgInfo.loadStatus = 'ok';
						reqData.msgInfo.id = res.id;
						reqData.msgInfo.sendId=res.sendId;
						if(res.groupMessage!=undefined){
							reqData.msgInfo.groupMessage = JSON.parse(res.groupMessage);
						}
						if(res.privateMessage!=undefined){
							reqData.msgInfo.privateMessage = JSON.parse(res.privateMessage);
						}
						this.isReceipt = false;
						setTimeout(()=>{
							// 插入消息
							this.chatStore.insertMessage(reqData.msgInfo);
						},2000);
						// 会话置顶
						this.moveChatToTop();
						// 滚到最低部
						this.scrollToBottom();
						uni.hideLoading();
						reqData.resolve(res)
					}).catch((e)=>{
						reqData.reject(e)
					}).finally(()=>{
						this.isSending = false;
						// 发送下一条请求
						this.processReqQueue2();
					})
				}
			},

			generateId(){
				// 生成临时id
				return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
			},

			getInfo(gid,type){
				groupApi.isprohibition(gid,type).then(data=>{
					 if(data){
						if(data=='1'){
							 this.isProhibition=true;
							 this.sendText="全  员   禁   言"
							 this.stylea="center";
						}else if(data=='2'){
							 this.isProhibition=true;
							 this.sendText="已  被   禁   言"
							 this.stylea="center";
						}else if(data=='0'){
							 this.isProhibition=false;
							 this.sendText=""
							 this.stylea="";
						}
					 }
				})
				var params={
					groupId:gid
				}
				groupMember.getPermission(params).then(res=>{
					this.isadmin=res;
						// if(res=='成功'){
						// 	this.isadmin=false;
						// }else{
						// 	this.isadmin=res;
						// }
					
				})
			},

			// 处理相册点击
			handleAlbumClick() {
				// #ifdef APP-PLUS
				if(plus.os.name.toLowerCase() === 'android') {
					requestPermissionWithExplanation('android.permission.READ_EXTERNAL_STORAGE')
						.then(() => {
							this.chooseAndUploadImage('album');
						})
						.catch(() => {
							uni.showToast({
								title: '未获得存储权限',
								icon: 'none'
							});
						});
				} else if(plus.os.name.toLowerCase() === 'ios') {
					// iOS 直接调用选择图片
					this.chooseAndUploadImage('album');
				}
				// #endif
			},

			// 处理拍摄点击
			handleCameraClick() {
				// #ifdef APP-PLUS
				if(plus.os.name.toLowerCase() === 'android') {
					requestPermissionWithExplanation('android.permission.CAMERA')
						.then(() => {
							this.chooseAndUploadImage('camera');
						})
						.catch(() => {
							uni.showToast({
								title: '未获得相机权限',
								icon: 'none'
							});
						});
				} else if(plus.os.name.toLowerCase() === 'ios') {
					// iOS 直接调用相机
					this.chooseAndUploadImage('camera');
				}
				// #endif
			},

			// 处理文件点击
			handleFileClick() {
				// #ifdef APP-PLUS
				if(plus.os.name.toLowerCase() === 'android') {
					requestPermissionWithExplanation('android.permission.READ_EXTERNAL_STORAGE')
						.then(() => {
							this.permission = true;
							uni.setStorageSync('file_permission_granted', 'true');
						})
						.catch(() => {
							uni.showToast({
								title: '未获得存储权限',
								icon: 'none'
							});
							this.permission = false;
							uni.removeStorageSync('file_permission_granted');
						});
				} else if(plus.os.name.toLowerCase() === 'ios') {
					// iOS 直接设置权限为 true
					this.permission = true;
					uni.setStorageSync('file_permission_granted', 'true');
				}
				// #endif
			},

			// 新增选择和上传图片的通用方法
			chooseAndUploadImage(sourceType) {
				uni.chooseImage({
					count: sourceType === 'camera' ? 1 : 9,
					sourceType: [sourceType],
					sizeType: ['original'],
					success: (res) => {
						res.tempFiles.forEach((file) => {
							// 添加sourceType到file对象
							file.sourceType = sourceType;
							if(this.onUploadImageBefore(file)) {
								uni.uploadFile({
									url: UNI_APP.BASE_URL + '/image/upload',
									header: {
										accessToken: uni.getStorageSync("loginInfo").accessToken
									},
									filePath: file.path,
									name: 'file',
									success: (uploadRes) => {
										let data = JSON.parse(uploadRes.data);
										if(data.code != 200) {
											uni.showToast({
												icon: "none",
												title: data.message,
											});
											this.onUploadImageFail(file, data);
										} else {
											this.onUploadImageSuccess(file, data);
										}
									},
									fail: (err) => {
										console.log(err);
										this.onUploadImageFail(file, err);
									}
								});
							}
						});
					},
					fail: (err) => {
						console.error(sourceType === 'camera' ? '拍照失败:' : '选择图片失败:', err);
					}
				});
			},

			onUploadImageBefore(file) {
				// #ifdef APP-PLUS
				if(plus.os.name.toLowerCase() === 'android') {
					const permissionName = file.sourceType === 'camera' 
						? 'android.permission.CAMERA'
						: 'android.permission.READ_EXTERNAL_STORAGE';
						
					return requestPermissionWithExplanation(permissionName)
						.then(() => {
							return this.createImageMessage(file);
						})
						.catch(() => {
							uni.showToast({
								title: file.sourceType === 'camera' ? '未获得相机权限' : '未获得存储权限',
								icon: 'none'
							});
							return false;
						});
				} else if(plus.os.name.toLowerCase() === 'ios') {
					// iOS 直接创建消息，不需要权限检查
					return this.createImageMessage(file);
				}
				// #endif
				return true;
			},

			// 新增创建图片消息的方法
			createImageMessage(file) {
				let data = {
					originUrl: file.path,
					thumbUrl: file.path
				}
				let msgInfo = {
					id: 0,
					tmpId: this.generateId(),
					fileId: file.uid,
					sendId: this.mine.id,
					content: JSON.stringify(data),
					sendTime: new Date().getTime(),
					selfSend: true,
					type: this.$enums.MESSAGE_TYPE.IMAGE,
					readedCount: 0,
					loadStatus: "loading",
					status: this.$enums.MESSAGE_STATUS.UNSEND,
				}
				this.fillTargetId(msgInfo, this.chat.targetId);
				this.chatStore.insertMessage(msgInfo);
				this.quoteShow = false;
				this.moveChatToTop();
				file.msgInfo = msgInfo;
				this.scrollToBottom();
				return true;
			},

			onUploadImageSuccess(file, res) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				console.log("res:", res);
				msgInfo.content = JSON.stringify(res.data);
				msgInfo.receipt = this.isReceipt;
				if(this.quoteShow){
					msgInfo.quoteId = this.quoteId;
				}
				this.sendMessageRequest(msgInfo).then((m) => {
					msgInfo.loadStatus = 'ok';
					msgInfo.id = m.id;
					msgInfo.sendNickName = m.sendNickName;
					this.isReceipt = false;
					this.chatStore.insertMessage(msgInfo);
					this.quoteShow = false; //关闭引用
				})
			},

			onUploadImageFail(file, err) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				msgInfo.loadStatus = 'fail';
				this.chatStore.insertMessage(msgInfo);
				this.quoteShow=false;//关闭引用
			},
		},
		computed: {
			groupInfo(){
				if(this.chat){
					if (this.chat.type == "GROUP") {
						let groupList=this.groupStore.groups;
						// this.$http({
						// 	url: `/group/members/${this.chat.targetId}`,
						// 	method: 'GET'
						// }).then((groupMembers) => {
						// 	this.groupMembers = groupMembers;
						// });
						this.getInfo(this.chat.targetId,this.chat.type);//查询禁言状态
						groupList.forEach((item)=>{
							if(item.id==this.chat.targetId){
								this.group=item;
								this.groupMembers = item.groupMembers;
								this.chatStore.updateChatFromGroup(item);
								this.groupStore.updateGroup(item);
								if(this.isadmin){
									this.AutoAdd=true;
								}else{
									this.AutoAdd=this.group.tempAutoAdd == 'Y' ? true :false;	
								}
								return item;
							}
						})
					}else{
						this.AutoAdd=true;
					}
				}
				
			},
			// AutoAdd(){
			// 	return this.group.tempAutoAdd == 'Y' ? true :false;
			// },
			mystyle(){
				return {
					textAlign: this.stylea
				};
			},
			mine() {
				return this.userStore.userInfo;
			},
			title() {
				if (!this.chat) {
					return "";
				}
				let title = this.chat.showName;
				if (this.chat.type == "GROUP") {
					let size = this.groupMembers ? this.groupMembers.length : 0;
					title += `(${size})`;
				}
				uni.setNavigationBarTitle({
					title: title
				});
				return title;
			},
			messageAction() {
				return `/message/${this.chat.type.toLowerCase()}/send`;
			},
			messageSize() {
				if (!this.chat || !this.chat.messages) {
					return 0;
				}
				return this.chat.messages.length;
			},
			unreadCount() {
				if (!this.chat || !this.chat.unreadCount) {
					return 0;
				}
				return this.chat.unreadCount;
			},
			atUserItems() {
				let atUsers = [];
				this.atUserIds.forEach((id) => {
					if (id == -1) {
						atUsers.push({
							id: -1,
							showNickName: "全体成员"
						})
						return;
					}
					let member = this.groupMembers.find((m) => m.userId == id);
					if (member) {
						atUsers.push(member);
					}
				})
				return atUsers;
			}
		},
		watch: {
			messageSize: function(newSize, oldSize) {
				// 接收到消息时滚动到底部
				if (newSize > oldSize) {
					let pages = getCurrentPages();
					let curPage = pages[pages.length-1].route;
					if(curPage == "pages/chat/chat-box"){
						this.scrollToBottom();
					}else {
						this.needScrollToBottom = true;
					}
				}
			},
			unreadCount: {
				handler(newCount, oldCount) {
					if (newCount > 0) {
						// 消息已读
						this.readedMessage()
					}
				}
			}
		},
		async onLoad(options) {
			// #ifdef APP-PLUS
			if(plus.os.name.toLowerCase() === 'android') {
				// 检查是否已经获得过文件权限
				const storageKey = 'file_permission_granted'
				const hasGranted = uni.getStorageSync(storageKey)
				if(hasGranted === 'true') {
					try {
						await requestPermissionWithExplanation('android.permission.READ_EXTERNAL_STORAGE')
						await requestPermissionWithExplanation('android.permission.WRITE_EXTERNAL_STORAGE')
						this.permission = true
					} catch(e) {
						this.permission = false
						uni.removeStorageSync(storageKey)
					}
				}
			}
			// #endif
			
			// 聊天数据
			this.chat = this.chatStore.chats[options.chatIdx];
			// 初始状态只显示20条消息
			let size = this.messageSize;
			this.showMinIdx = size > 20 ? size - 20 : 0;
			// 消息已读
			this.readedMessage();
			if(this.chat){
				// 加载好友或群聊信息
				if (this.chat.type == "GROUP") {
					this.loadGroup(this.chat.targetId);
					this.getInfo(this.chat.targetId, this.chat.type);
				} else if (this.chat.type == "SYSTEM") {
					this.loadSystemInfo();
				} else {
					this.loadFriend(this.chat.targetId);
					this.loadReaded(this.chat.targetId);
					this.stylea = "";
					this.isProhibition = false;
				}
			}
			// 激活前会话
			this.chatStore.activeChat(options.chatIdx);
			// 复位回执消息
			this.isReceipt = false;
		},
		onShow(){
			uni.setNavigationBarTitle({
				title: this.title
			});
			if(this.needScrollToBottom){
				// 页面滚到底部
				this.scrollToBottom();
				this.needScrollToBottom = false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 这里使用scss语法，你也可以根据喜好使用css语法
	.container {
	    padding: 20px;
	}
	
	// 针对u-alert组件内部显示文字的部分设置样式
	.ellipsis-alert.u-alert__message {
	    overflow: hidden;
	    white-space: nowrap;
	    text-overflow: ellipsis;
	    max-width: 200px; // 设置一个最大宽度，当文字超出这个宽度时显示省略号
	}
	.chat-box {
		position: relative;
		border: #dddddd solid 1px;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;

		.header {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 60rpx;
			padding: 5px;
			background-color: #f8f8f8;
			line-height: 50px;
			font-size: 36rpx;
			border: #dddddd solid 1px;

			.btn-side {
				position: absolute;
				line-height: 60rpx;
				font-size: 28rpx;
				cursor: pointer;

				&.right {
					right: 30rpx;
				}
			}
		}

		.chat-msg {
			flex: 1;
			padding: 0;
			border: #dddddd solid 1px;
			overflow: hidden;
			position: relative;
			background-color: #f5f5f5;

			.scroll-box {
				height: 100%;
			}
		}
		.chat-yy-bar {//引用消息样式
					display: flex;
					align-items: center;
					padding: 0 10rpx;
					border: #dddddd solid 1px;

					.icon-at {
						font-size: 35rpx;
						color: darkblue;
						font-weight: 600;
					}

					.chat-at-scroll-box {
						flex: 1;
						width: 80%;

						.chat-at-items {
							display: flex;
							align-items: center;
							height: 70rpx;

							.chat-at-item {
								padding: 0 3rpx;
							}
						}
					}

				}
		.chat-at-bar {
			display: flex;
			align-items: center;
			padding: 0 10rpx;
			border: #dddddd solid 1px;

			.icon-at {
				font-size: 35rpx;
				color: darkblue;
				font-weight: 600;
			}

			.chat-at-scroll-box {
				flex: 1;
				width: 80%;

				.chat-at-items {
					display: flex;
					align-items: center;
					height: 70rpx;

					.chat-at-item {
						padding: 0 3rpx;	
					}
				}
			}

		}

		.send-bar {
			display: flex;
			align-items: center;
			padding: 10rpx;
			margin-bottom: 0;
			border: #dddddd solid 1px;
			background-color: #f5f5f5;
			min-height: 80rpx;
			max-height: 300rpx;
			
			.iconfont {
				font-size: 60rpx;
				margin: 6rpx;
				display: flex;
				align-items: center;
				height: 60rpx;
				width: 60rpx;
				justify-content: center;
			}

			.chat-record {
				flex: 1;
			}

			.send-text {
				flex: 1;
				overflow: hidden;
				padding: 10rpx 20rpx;
				margin: 5rpx 0;
				background-color: #fff;
				border-radius: 20rpx;
				font-size: 30rpx;
				box-sizing: border-box;
				min-height: 60rpx;
				max-height: 240rpx;
				display: flex;
				align-items: center;
				
				.send-text-area {
					width: 100%;
					min-height: 40rpx;
					line-height: 40rpx;
					padding: 0;
					margin: 0;
					height: auto;
					box-sizing: border-box;
					overflow: visible;
				}
			}

			.btn-send {
				margin: 5rpx;
				height: 60rpx;
				line-height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}


		.chat-tab-bar {
			height: 500rpx;
			padding: 20rpx;
			background-color: #f5f5f5;

			.chat-tools {
				display: flex;
				flex-wrap: wrap;

				.chat-tools-item {
					width: 140rpx;
					padding: 16rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
						
					.tool-icon {
						padding: 28rpx;
						font-size: 60rpx;
						border-radius: 20%;
						background-color: white;
						color: black;
						&.active {
							background-color: #ddd;
						}
					}

					.tool-name {
						height: 60rpx;
						line-height: 60rpx;
						font-size: 28rpx;
					}
				}
			}

			.chat-emotion {
				height: 100%;

				.emotion-item-list {
					display: flex;
					flex-wrap: wrap;

					.emotion-item {
						width: 40px;
						height: 40px;
						text-align: center;
						cursor: pointer;
						padding: 6px;
					}
				}
			}

		}
	}
</style>